package com.orangelife.mobile.confirmOrder.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.common.jump.CommonJumper;
import com.common.jump.VoucherJumper;
import com.common.sp.ShoppingSp;
import com.common.sp.UserSp;
import com.curry.android.http.HttpUtil;
import com.curry.android.http.VolleyHttpUtil;
import com.curry.android.util.DecimalUtil;
import com.curry.android.util.DialogHelper;
import com.curry.android.util.IntentHelper;
import com.curry.android.util.JSONHelper;
import com.curry.android.util.StringUtil;
import com.curry.android.util.ToastHelper;
import com.curry.orangelife.mobile.R;
import com.orangelife.mobile.address.activity.MakeAddressListActivity;
import com.orangelife.mobile.app.application.ExitApplication;
import com.orangelife.mobile.common.activity.OrangeLifeBaseActivity;
import com.orangelife.mobile.common.biz.JSONRequest;
import com.orangelife.mobile.constants.ConfirmOrderURL;
import com.orangelife.mobile.voucher.biz.VoucherBiz;
import com.orangelife.mobile.voucher.biz.VoucherHttpBiz;
import com.orangelife.mobile.constants.Constant;
import com.orangelife.mobile.pay.activity.UsersPaidActivity;
import com.orangelife.mobile.pay.biz.PaymentModule;
import com.orangelife.mobile.voucher.biz.SelectedVoucherIDListHelper;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 缴费确认订单页面（涉及模块：维修、停车费、物业缴费账单、清洁）
 *
 * @author Administrator
 */
public class PayConfirmOrderActivity extends OrangeLifeBaseActivity {

    /** 信息 */
    private TextView tvInformation;
    /** 价钱 */
    private TextView tvMoney;
    /** linearlayout */
    private LinearLayout llVoucher;
    /** 抵用券 */
    private TextView tvVoucherInfo;
    /** 标题 */
    private TextView tvTitle;
    /** 总价 */
    private TextView tvPayPrice;
    /** 底部抵用券 */
    private TextView tvPayVoucher;
    /** 底部支付 */
    private TextView tvPay;
    /** 停车费信息 */
//	private TextView tvParking;

    private TextView tvName;

    private TextView tvPhone;

    private TextView tvAddress;

    private TextView tvTitleRight;
    private static final int WHAT_PAY = 0;
    private String totalPrice;
    private String city, comm, floor, house, payment, parkID, parkingLot, licensePlate, apartmentID, billID, repaireCode, serviceOrderID, orderInfo;
    private String type;
    private int feeType;
    private LinearLayout llAddress;
    private Intent intent;
    private String price;
    private String voucherInfo = VoucherBiz.STR_NO_VOUCHER;
    private String voucherID;
    private boolean needVoucher;
    private Map<String, Object> commitInfoMap;
    private String defaultVoucherKey = "0";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay_confirm_order);
        intent = getIntent();
        getIntentInfo();
        initView();
        setListener();
        setDetail();
        if (needVoucher) {
            requestVoucherHighestPrice();
        }
    }

    private void getIntentInfo() {
        city = intent.getStringExtra("City");
        comm = intent.getStringExtra("Comm");
        floor = intent.getStringExtra("Floor");
        house = intent.getStringExtra("House");
        payment = intent.getStringExtra("Payment");
        type = intent.getStringExtra(PaymentModule.PAID_METHOD);
        feeType = intent.getIntExtra("feeType", -1);
        billID = intent.getStringExtra("billID");
        apartmentID = intent.getStringExtra("apartmentID");
        parkID = intent.getStringExtra("parkID");
        parkingLot = intent.getStringExtra("ParkingLot");
        licensePlate = intent.getStringExtra("LicensePlate");
        repaireCode = intent.getStringExtra("repaireCode");
        serviceOrderID = intent.getStringExtra("serviceOrderID");
        orderInfo = intent.getStringExtra("orderInfo");
        commitInfoMap = (Map<String, Object>) intent
                .getSerializableExtra("map");
    }

    private void initView() {
        tvTitleRight = (TextView) findViewById(R.id.tv_title_right);
        tvInformation = (TextView) findViewById(R.id.tvInformation);
        tvName = (TextView) findViewById(R.id.tv_username);
        tvPhone = (TextView) findViewById(R.id.tv_userphone);
        tvAddress = (TextView) findViewById(R.id.tv_address);
        tvMoney = (TextView) findViewById(R.id.tvMoney);
        llVoucher = (LinearLayout) findViewById(R.id.llVoucher);
        tvVoucherInfo = (TextView) findViewById(R.id.tvVoucherInfo);
        tvTitle = (TextView) findViewById(R.id.tv_title);
        tvPayPrice = (TextView) findViewById(R.id.tvPayPrice);
        tvPayVoucher = (TextView) findViewById(R.id.tvPayVoucher);
        tvPay = (TextView) findViewById(R.id.tvPay);
        llAddress = (LinearLayout) findViewById(R.id.llAddAddress);
        tvTitle.setText("确认订单");
        tvTitleRight.setVisibility(View.GONE);
    }

    private void setListener() {
        tvPay.setOnClickListener(listener);
        llVoucher.setOnClickListener(listener);
        llAddress.setOnClickListener(listener);
    }

    @SuppressLint("ResourceAsColor")
    private void setDetail() {
        llVoucher.setVisibility(View.GONE);
        if (type.equals(PaymentModule.mode[3])) {/*维修*/
            switch (feeType) {
                case 0:
                    needVoucher = false;
                    tvInformation.setText("维修估价单");
                    llVoucher.setVisibility(View.GONE);
                    llAddress.setVisibility(View.GONE);
                    break;
                case 1:
                    needVoucher = false;
                    tvInformation.setText("维修定价单差额");
                    llVoucher.setVisibility(View.GONE);
                    llAddress.setVisibility(View.GONE);
                    break;
                case 2:
                    // TODO: 2016/3/16 存在一个BUG，订单跳转到抵用券列表，可能多个抵用券被勾选，不选择退回来，就会变成未使用抵用券
                    /*暂时关闭此维修的抵用券*/
                    needVoucher = false;//true
                    llVoucher.setVisibility(View.GONE);//VISIBLE

                    llAddress.setVisibility(View.VISIBLE);
                    tvInformation.setText("维修上门费");
                    @SuppressWarnings("unchecked")
                    Map<String, Object> map = (Map<String, Object>) getIntent()
                            .getSerializableExtra("map");
                    tvName.setText(map.get("shipName").toString());
                    tvPhone.setText(map.get("shipAddr").toString());
                    tvAddress.setText(map.get("shipPhone").toString());
                    break;
                default:
                    break;
            }
        } else {
            needVoucher = false;
            if (type.equals(PaymentModule.mode[4])) {/*物业费*/
                tvInformation.setText(comm + "小区" + " " + floor + "号楼" + " " + house);
            } else if (type.equals(PaymentModule.mode[8])) {/*钟点工*/
                llAddress.setVisibility(View.GONE);
                tvInformation.setText(orderInfo);
            }
        }
        tvMoney.setText(Constant.RMB_FLAG + payment);
        tvPayPrice.setText(Constant.RMB_FLAG + payment);
        totalPrice = payment;
        price = totalPrice;
    }

    /** 取金额最高的抵用券 */
    private void requestVoucherHighestPrice() {
        showDialog(this);
        VoucherHttpBiz.getVoucherHighestPriceListWithService(price, VoucherHttpBiz.TYPE_REPAIR, new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject response, int errCode) {
                closeDialog();
                List<Map<String, Object>> highestPriceVoucherList = VoucherHttpBiz.handleVoucherHighestPriceList(response);
                if (highestPriceVoucherList != null && highestPriceVoucherList.size() > 0) {
                    voucherInfo = String.valueOf(highestPriceVoucherList.get(0).get("money")) + "元抵用券";
                    voucherID = String.valueOf(highestPriceVoucherList.get(0).get("couponID"));
                    VoucherBiz.setVoucherInfoBackground(tvVoucherInfo, voucherInfo, PayConfirmOrderActivity.this);
                        /*维修并没有ID，所以使用“0”，作为抵用券的KEY*/
                    SelectedVoucherIDListHelper.getInstance().addSelectedVoucherID(voucherID, defaultVoucherKey);
                }
            }
        });
    }

    private OnClickListener listener = new OnClickListener() {

        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.tvPay:
                    showDialog(PayConfirmOrderActivity.this);
                    if (type.equals(PaymentModule.mode[3])) {/*维修费*/
                        if (feeType == 0 || feeType == 1) {
                            requestAddAppraiseOrder();
                        } else {
                            requestAddRepairOrder();
                        }
                    } else if (type.equals(PaymentModule.mode[4])) {
                        requestCommitPropertyOrder();
                    } else if (type.equals(PaymentModule.mode[8])) {
                        requestCommitHourlyEmployeeOrder();
                    }
                    break;
                case R.id.llAddAddress:
                    if (!hasTokenFromLocal()) {
                        requestTokenStatusBeforeJumpAddress();
                    } else {
                        jumpToLogin();
                    }
                    break;
                case R.id.llVoucher:
                    jumpToVoucherListForResult();
                    break;
                default:
                    break;
            }
        }
    };

    /** 获取用户会话登录状态,是否可用 */
    private void requestTokenStatusBeforeJumpAddress() {
        Map<String, Object> map = new HashMap<>();
        map.put("{accessToken}", UserSp.getAccessToken());
        JSONRequest.getInstance().sendRequest(JSONRequest.GET, Constant.URL_ACCESSTOKEN, map, handler, 13, HttpUtil.ACTION_URI);
    }

    private void handleTokenStatus(String response) {
        HashMap<String, Object> entityMap = (HashMap<String, Object>) JSONHelper.jsonToMap(
                response);
        if (entityMap == null) {
            return;
        }
        HashMap<String, Object> mapAccessToken = (HashMap<String, Object>) entityMap.get("entity");
        String isOnlineToken = String.valueOf(mapAccessToken.get("online"));
        if ("true".equals(isOnlineToken)) {
            jumpToAddress();
        } else {
            jumpToLogin();
        }
    }

    private boolean hasTokenFromLocal() {
        if (StringUtil.isBlank(UserSp.getLoginID())) {
            return false;
        }
        return true;
    }

    private void jumpToLogin() {
        ToastHelper.getInstance()._toast("请先登录");
        CommonJumper.jumpToLoginWhenExitWithClear(PayConfirmOrderActivity.this);
    }

    private void jumpToAddress() {
        IntentHelper.getInstances().getIntent(PayConfirmOrderActivity.this, MakeAddressListActivity.class);
    }

    @SuppressWarnings("unchecked")
    private void jumpToPay(Map<String, Object> map) {
        Bundle bundle = getPayParam(map);
        bundle.putString("status", "pays");
        Intent intent = new Intent(PayConfirmOrderActivity.this, UsersPaidActivity.class);
        intent.putExtras(bundle);
        startActivity(intent);
        finish();
        ExitApplication.getInstance().addPaidActivity(PayConfirmOrderActivity.this);
    }


    /** 传递到支付页面的值 */
    private Bundle getPayParam(Map<String, Object> map) {
        Bundle bundle = new Bundle();
        bundle.putString("totalCost", map.get("totalCost").toString());
//		bundle.putString("money",map.get("money").toString());
        bundle.putString("couponCost", map.get("couponCost").toString());
        bundle.putString("outtradeno", map.get("outtradeno").toString());
//		if(type!=3){
//			bundle.putString("orderID", map.get("orderID").toString
        //		}
        bundle.putString("tvPayPrice", price + "");
        bundle.putString("totalPrice", Constant.RMB_FLAG + DecimalUtil.subtract(totalPrice, map.get("couponCost").toString()));
        bundle.putString("orderInfo", map.get("orderContent").toString());
        bundle.putString("serviceOrderID", serviceOrderID);
        if (feeType == 2) {
            bundle.putString("repairID", map.get("repairID").toString());
        }
        bundle.putString(PaymentModule.PAID_METHOD, type);
        bundle.putString("orderType", String.valueOf(map.get("orderType")));
        bundle.putInt("feeType", feeType);
        return bundle;
    }


    /** 跳转到抵用券列表 */
    private void jumpToVoucherListForResult() {
        if (VoucherBiz.STR_NO_VOUCHER.equals(voucherInfo)) {
            ToastHelper.getInstance()._toast("暂无抵用券");
            return;
        }
        VoucherJumper.jumpToVoucherListWithService(this, totalPrice);/*跳转到选择抵用券列表界面*/
        VoucherHttpBiz.cancelVoucherHighestPriceList();/*为了避免进入抵用券列表，选中抵用券后，原先最高金额抵用券的值才返回来的情况出现，如果超时没回来，就取消请求*/
        SelectedVoucherIDListHelper.getInstance().setVoucherListMapKey(defaultVoucherKey);
    }

    private void handleJumpBackVoucher() {
        //                showVoucher(data, tvCoupons, mTotalCost, tvPropertyNum);
                /*唯一有用的，其实只是抵用券ID而已*/
        ArrayList<String> voucherIDList = SelectedVoucherIDListHelper.getInstance().getSelfVoucherList();
        if (voucherIDList != null && voucherIDList.size() == 1) {
            voucherID = voucherIDList.get(0);
        }
        String newVoucherInfo = VoucherBiz.getVoucherInfo(voucherInfo);
        VoucherBiz.setVoucherInfoBackground(tvVoucherInfo, newVoucherInfo, this);
    }


    @SuppressLint("ResourceAsColor")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        handleJumpBackVoucher();
    }

    /** 物业缴费订单 */
    private void requestCommitPropertyOrder() {
        Map<String, Object> map = new HashMap<>();
        map.put("apartmentID", apartmentID);
        map.put("orderInfo", city + comm + floor + house);
        map.put("totalCost", payment);
        map.put("couponID", voucherID);
        map.put("orderContent", tvInformation.getText().toString());
        JSONRequest.getInstance().sendRequest(JSONRequest.POST, ConfirmOrderURL.PROPERTYORDER, map, handler, WHAT_PAY, HttpUtil.ACTION_JSON);
    }

    /** 清洁订单 */
    private void requestCommitHourlyEmployeeOrder() {
        String url = Constant.URL_HOURLY_EMPLOYEE_CONFIRE_ORDER;
        Map<String, Object> map = new HashMap<>();
        map.put("serviceOrderID", serviceOrderID);
        map.put("couponID", voucherID);
        JSONRequest.getInstance().sendRequest(JSONRequest.POST, url, map, handler, WHAT_PAY, HttpUtil.ACTION_JSON);
    }

    /** 添加估价定单 */
    private void requestAddAppraiseOrder() {
        String url = Constant.APPRAISE_ADD;
        Map<String, Object> map = new HashMap<>();
        map.put("billID", billID);
        map.put("repaireCode", repaireCode);
        map.put("couponID", voucherID);
        JSONRequest.getInstance().sendRequest(JSONRequest.POST, url, map, handler, WHAT_PAY, HttpUtil.ACTION_JSON);
    }

    /** 添加"找维修"的订单 */
    private void requestAddRepairOrder() {
        String url = Constant.URL_LOOKREPAIR_ADD;
        Map<String, Object> map = new HashMap<>();
        if (commitInfoMap != null) {
            String orderInfo = String.valueOf(commitInfoMap.get("orderInfo"));
            map.put("orderInfo", orderInfo);
            String pics = String.valueOf(commitInfoMap.get("pics"));
            if (pics != null && !pics.equals("")
                    && !pics.equals("null")) {
                map.put("pics", pics);
            }
        }
//			map.put("shipName", tvName.getText().toString());
//			map.put("shipAddr", tvAddress.getText().toString());
//			map.put("shipPhone", tvPhone.getText().toString());
        map.put("addressID", ShoppingSp.getTradeAddressID());
        map.put("couponID", voucherID);
        JSONRequest.getInstance().sendRequest(JSONRequest.POST, url, map, handler, WHAT_PAY, HttpUtil.ACTION_JSON);
    }

    private void handleCommitOrder(String response) {
        Map<String, Object> entityMap = JSONHelper.jsonToMap(
                response);
        if (entityMap != null) {
            Map<String, Object> map = (Map<String, Object>) entityMap.get("entity");
            jumpToPay(map);
        }
    }

    /**
     * 处理返回的信息数据
     */
    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            closeDialog();
            String response = String.valueOf(msg.obj);
            switch (msg.what) {
                case 9:
                    Map<String, Object> mapDetail = new HashMap<>();
                    mapDetail = (Map<String, Object>) JSONHelper.jsonToMap(
                            msg.obj.toString()).get("entity");
//				setDetail();
                    break;
                case 1011:
                    isLogin(dialog);
                    break;
                case 1003:
                    ToastHelper.getInstance()._toast(
                            getResources().getString(R.string.code_1003));
                    break;
                case 500:
                    ToastHelper.getInstance()._toast(
                            response);
                    break;
                case WHAT_PAY:
                    handleCommitOrder(response);
                    break;
                case 13:
                    handleTokenStatus(response);
                    break;
                default:
                    break;
            }
            DialogHelper.closeDialog(dialog);
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SelectedVoucherIDListHelper.getInstance().destroyBiz();
    }
}
